package com.hmdp.utils;


import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

@Component
@Slf4j
public class CacheClient {

    private static final ExecutorService CACHE_EXECUTOR = Executors.newFixedThreadPool(10);


    private StringRedisTemplate stringRedisTemplate;
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }
    public void setWithLogicalExpire(String key, Object value, Long expire, TimeUnit timeUnit) {

        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(expire)));
        redisData.setData(value);

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    public  <T,ID> T queryWhthPassThrouth(String keyPrefix, ID id, Class<T> type, Function<ID,T> dbFallback, Long time, TimeUnit timeUnit) {

            //redis 查询
            String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
            if (StrUtil.isNotBlank(json)) {
                T ans = JSONUtil.toBean(json, type);

                return ans;
            }
            if(json != null){
                return null;
            }
            //缓存没有命中获取锁
            String lockKey = LOCK_SHOP_KEY + id;


            Shop shop;

            //查询数据库
            T r = dbFallback.apply(id);
            //不存在
            if (r == null) {
                stringRedisTemplate.opsForValue().set(keyPrefix+ id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

                return null;
            }
            //存在,写入redis
            setWithLogicalExpire(keyPrefix+ id,r, time, timeUnit);


        return r;

    }
    public  <T,ID> T queryWithMutex(String keyPrefix, ID id, Class<T> type, Function<ID,T> dbFallback, Long time, TimeUnit timeUnit){
        while (true) {
            //redis 查询
            String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
            if (StrUtil.isNotBlank(json)) {
                T r = JSONUtil.toBean(json, type);

                return r;
            }
            if(json != null){
                return null;
            }
            //缓存没有命中获取锁
            String lockKey = LOCK_SHOP_KEY + id;
            boolean result = tryLock(lockKey);
            if(!result){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                continue;
            }
            Shop shop;
            try {
                //查询数据库
                T r = dbFallback.apply(id);
                //不存在
                if (r == null) {
                    this.set(keyPrefix + id, "", time, timeUnit);

                    return null;
                }

                //存在,写入redis
                this.set(keyPrefix + id, JSONUtil.toJsonStr(r),time, timeUnit);
                return r;

            } finally {
                //释放互斥锁
                unlock(lockKey);
            }


        }
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
